const jwt = require('jsonwebtoken');
const { jwtConfig } = require("../../config/conifg");
const { jwtSecret, whiteList } = jwtConfig;
const { Fail } = require("./status");
var send = new Fail({
    msg: "请登录！"
})
function sign(obj) {
    return jwt.sign(obj, jwtSecret, { expiresIn: '24h' })
}
function verify(authorization) {
    try {
        return jwt.verify(authorization, jwtSecret)
    } catch (e) {
        return false
    }
}
async function koaJwt(ctx, next) {
    const { authorization = '' } = ctx.request.header;
    if (whiteList.includes(ctx.request.url) || ctx.request.method == "GET") {
        await next()
    } else {
        const user = verify(authorization);
        if (user) {
            ctx.state.user = user
            await next()
        } else {
            ctx.body = send
        }
    }
}
module.exports = {
    koaJwt,
    verify,
    sign
}